package org.inspursc.s0517.health.common.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.inspursc.s0517.health.common.converter.GroupConverter2SysGroup;
import org.inspursc.s0517.health.common.entity.SysGroup;
import org.inspursc.s0517.health.common.enums.ResultEnum;
import org.inspursc.s0517.health.common.exception.BizException;
import org.inspursc.s0517.health.common.form.GroupForm;
import org.inspursc.s0517.health.common.service.SysGroupService;
import org.inspursc.s0517.health.common.util.ResponseUtil;
import org.inspursc.s0517.health.common.vo.ResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping(value = "/api/group")
@Api(value = "权限组操作的Controller")
public class SysGroupController {

    @Autowired
    private SysGroupService groupService;

    @ApiOperation(value = "获取表单信息，新增保存权限组")
    @PostMapping(value = "/save")
    public ResponseEntity<ResponseVO> save(@Valid GroupForm groupForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        SysGroup sysGroup = GroupConverter2SysGroup.converter(groupForm);
        SysGroup group = groupService.save(sysGroup);
        if (null != group) {
            return ResponseUtil.success("保存成功", group);
        }
        return ResponseUtil.error("保存失败", group);
    }

    @ApiOperation(value = "根据组ID，删除权限组")
    @GetMapping("/delete/{id}")
    public ResponseEntity<ResponseVO> delete(@ApiParam(value = "组ID", required = true) @PathVariable Integer id) {
        boolean is = groupService.deleteById(id);
        if (is) {
            return ResponseUtil.success("删除成功", is);
        }
        return ResponseUtil.error("删除失败", is);
    }


    @ApiOperation(value = "根据组ID，获取权限组信息")
    @GetMapping("/get/{id}")
    public ResponseEntity<ResponseVO> get(@ApiParam(value = "组ID", required = true) @PathVariable Integer id) {
        SysGroup sysGroup = groupService.findById(id);
        return ResponseUtil.success("", sysGroup);
    }


    @ApiOperation(value = "获取所有权限组")
    @PostMapping(value = "/getAll")
    public ResponseEntity<ResponseVO> getAll() {

        List<SysGroup> sysGroupList = groupService.findAll();

        return ResponseUtil.success(sysGroupList);
    }

}
